package com.monitor.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.monitor.dao.CallLogDao;
import com.monitor.po.CallLog;
import com.monitor.util.Pager;

@SuppressWarnings("unchecked")
public class CallLogDaoImpl implements CallLogDao {
	private SessionFactory sessionFactory;

	@Override
	public Pager<CallLog> getCallLogByUid(long uid, int pageSize, int currentPage) throws Exception {
		try {
			Session sesion = this.sessionFactory.getCurrentSession();
			Query query = sesion.createQuery("select count(*) from CallLog c where c.ownerUid=:ownerUid").setLong("ownerUid", uid);
			int totalCount = ((Number) query.uniqueResult()).intValue();
			int pageCount = (totalCount % pageSize == 0) ? totalCount / pageSize : (totalCount / pageSize) + 1;

			List<CallLog> list = sesion.createQuery("from CallLog c where c.ownerUid=:ownerUid order by c.id desc")
					.setLong("ownerUid", uid).setFirstResult((currentPage - 1) * pageSize).setMaxResults(pageSize).list();
			Pager<CallLog> pager = new Pager<CallLog>(list, currentPage, totalCount, pageCount);
			return pager;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("exception occured when excuting getCallLogByUid()....");
		}
	}

	@Override
	public void saveCallLog(CallLog log) throws Exception {
		try {
			sessionFactory.getCurrentSession().persist(log);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("exception occured when excuting saveCallLog()....");
		}
	}

	@Override
	public int deleteCalllogByUid(long uid) throws Exception {
		try {
			return sessionFactory.getCurrentSession().createQuery("delete from CallLog c where c.ownerUid =:ownerUid")
					.setLong("ownerUid", uid).executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("exception occured when excuting deleteCalllogByUid()....");
		}
	}

	@Override
	public CallLog getCalllogById(Long id) throws Exception {
		try {
			return (CallLog) sessionFactory.getCurrentSession().get(CallLog.class, id);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("exception occured when excuting getCalllogById()....");
		}
	}

	@Override
	public void deleteCalllog(CallLog log) throws Exception {
		try {
			sessionFactory.getCurrentSession().delete(log);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("exception occured when excuting deleteCalllog()....");
		}
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

}
